﻿using DrawIO45.Models.DrawIOs;
using DrawIO45.Models.Logic;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Schema;

namespace DrawIO45.Draws.Business
{
    /// <summary>
    /// 清理孤岛
    /// </summary>
    public class ClearIsolatedIsland : IDrawOnRoot
    {
        public void DrawOnRoot(Root root, List<DILocationInfo<LClassInfo>> classInfos)
        {
            // 清理掉孤岛
            var itemIds = new List<string>();

            var lines = root.MxCells.Where(IsLine).ToList();
            if (lines?.Any() == true)
            {
                foreach (var line in lines)
                {
                    itemIds.Add(line.Target);
                    itemIds.Add(line.Source);
                }
            }

            var matchClearItemFunc = new List<Func<MxCell, bool>>
            {
                new Func<MxCell, bool>(mx => RootIds.Contains(mx.Id)),      // 根节点不能删
                new Func<MxCell, bool>(mx => itemIds.Contains(mx.Id)),      // 有关系的不能删
                new Func<MxCell, bool>(mx => itemIds.Contains(mx.Parent)),  // 有关系的子类不能删
                IsLine,                                                     // 线对象不能删
            };

            // 任意一个为true 则不能删除
            root.MxCells.RemoveAll(IsCanDelete);

            bool IsCanDelete(MxCell cell)
            {
                foreach (var item in matchClearItemFunc)
                {
                    if (item(cell))
                        return false;
                }

                return true;
            }
        }

        string[] RootIds = new[] { "0", "1" };

        bool IsLine(MxCell cell)
        {
            if (string.IsNullOrEmpty(cell.Target))
                return false;

            if (string.IsNullOrEmpty(cell.Source))
                return false;

            return true;
        }
    }
}
